<?php
namespace TwOauth;

/**
 * Description of TwSdk
 *
 * @author company
 */
class TwSdk extends Tongwei
{

    private $keysArr;

    private $APIMap;

    public function __construct($access_token, $redirect_uri = '')
    {
        parent::__construct($redirect_uri);
        $this->keysArr = array(
            "app_key" => self::APP_KEY,
            "access_token" => $access_token
        );
        
        // 初始化APIMap
        /*
         * 加#表示非必须，无则不传入url(url中不会出现该参数)， "key" => "val" 表示key如果没有定义则使用默认值val
         * 规则 array( baseUrl, argListArr, method)
         */
        $this->APIMap = array(
            "get_user_info" => array(
                Config::getUserInfo(),
                array(),
                "GET"
            ),
            'get_user_profile' => array(
                Config::getUserProfile(),
                array(),
                "GET"
            )
        );
    }
    
    // 调用相应api
    private function _applyAPI($arr, $argsList, $baseUrl, $method)
    {
        $pre = "#";
        $keysArr = $this->keysArr;
        $optionArgList = array(); // 一些多项选填参数必选一的情形
        foreach ($argsList as $key => $val) {
            $tmpKey = $key;
            $tmpVal = $val;
            
            if (! is_string($key)) {
                $tmpKey = $val;
                
                if (strpos($val, $pre) === 0) {
                    $tmpVal = $pre;
                    $tmpKey = substr($tmpKey, 1);
                    if (preg_match("/-(\d$)/", $tmpKey, $res)) {
                        $tmpKey = str_replace($res[0], "", $tmpKey);
                        $optionArgList[$res[1]][] = $tmpKey;
                    }
                } else {
                    $tmpVal = null;
                }
            }
            
            // -----如果没有设置相应的参数
            if (! isset($arr[$tmpKey]) || $arr[$tmpKey] === "") {
                
                if ($tmpVal == $pre) { // 则使用默认的值
                    continue;
                } else 
                    if ($tmpVal) {
                        $arr[$tmpKey] = $tmpVal;
                    } else {
                        $this->error->showError("api调用参数错误", "未传入参数$tmpKey");
                    }
            }
            
            $keysArr[$tmpKey] = $arr[$tmpKey];
        }
        // 检查选填参数必填一的情形
        foreach ($optionArgList as $val) {
            $n = 0;
            foreach ($val as $v) {
                if (in_array($v, array_keys($keysArr))) {
                    $n ++;
                }
            }
            
            if (! $n) {
                $str = implode(",", $val);
                $this->error->showError("api调用参数错误", $str . "必填一个");
            }
        }
        
        if ($method == "GET") {
            $response = $this->urlUtils->get($baseUrl, $keysArr);
        } else {
            $response = $this->urlUtils->post($baseUrl, $keysArr);
        }
        return $response;
    }

    /**
     * _call
     * 魔术方法，做api调用转发
     *
     * @param string $name
     *            调用的方法名称
     * @param array $arg
     *            参数列表数组
     * @since 5.0
     * @return array 返加调用结果数组
     */
    public function __call($name, $arg)
    {
        // 如果APIMap不存在相应的api
        if (empty($this->APIMap[$name])) {
            $this->error->showError("api调用名称错误", "不存在的API: <span style='color:red;'>$name</span>");
        }
        
        // 从APIMap获取api相应参数
        $baseUrl = $this->APIMap[$name][0];
        $argsList = $this->APIMap[$name][1];
        $method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";
        
        if (empty($arg)) {
            $arg[0] = null;
        }
        
        $responseArr = json_decode($this->_applyAPI($arg[0], $argsList, $baseUrl, $method), TRUE);
        // 检查返回ret判断api是否成功调用
        if (! isset($responseArr['error'])) {
            return $responseArr;
        } else {
            $this->error->showError($responseArr['error'], $responseArr['error_description']);
        }
    }
}
